<!--
 * @Date: 2022-01-02 12:27:27
 * @LastEditors: LeeKing
 * @LastEditTime: 2022-01-05 14:58:47
 * @FilePath: \hmmm-20220102\src\module-manage\pages\permissions.vue
-->
<!--
 * @Date: 2022-01-02 12:27:27
 * @LastEditors: LeeKing
 * @LastEditTime: 2022-01-03 20:58:25
 * @FilePath: \hmmm-20220102\src\module-manage\pages\permissions.vue
-->
<template>
  <div>
    <!-- // ~卡片 -->
    <el-card class="box-card">
      <!-- // ~左侧盒子 -->
      <div class="left-box">
        <!-- // ~输入搜索框 -->
        <el-input
          v-model="input"
          placeholder="根据用户名搜索"
          class="inputSearch"
          @keyup.enter.native="inputChange"
        ></el-input>
        <el-button size="small" @click="clearBtn">清除</el-button>
        <el-button size="small" type="primary" @click="SearchBtn"
          >搜索</el-button
        >
      </div>
      <!-- // ~右侧盒子 -->
      <div class="right-box">
        <el-button
          size="small"
          type="success"
          icon="el-icon-edit"
          @click="addFn"
          >新增权限组</el-button
        >
      </div>

      <!-- // ~消息记录提示 -->
      <div class="MessageAlert">
        <el-alert type="info" class="MessageAlert" :closable="false">
          <template>
            <i class="el-icon-info"></i> 共{{ counts }}条记录</template
          >
        </el-alert>
      </div>

      <!-- // ~From表格 -->
      <div class="From-box">
        <el-table
          ref="multipleTable"
          :data="tableData"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection"> </el-table-column>

          <el-table-column prop="title" label="用户名"> </el-table-column>

          <el-table-column label="日期" sortable>
            <template slot-scope="{ row }">
              {{ parseTime(row.create_date) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="address"
            label="操作"
            show-overflow-tooltip
            fixed="right"
            width="120"
          >
            <template slot-scope="{ row }">
              <!-- // ~编辑权限组 -->
              <el-button
                type="primary"
                icon="el-icon-edit"
                plain
                circle
                @click="EditBtn(row.id)"
              ></el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                plain
                @click="removeBtn(row)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- // ~ 分页 -->
      <div class="paging">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          layout=" prev, pager, next,sizes, jumper"
          :total="total"
          background
        >
        </el-pagination>
      </div>

      <!-- // ~弹框 - 创建权限组 -->
      <div class="pop-up">
        <el-dialog
          :title="title"
          :visible.sync="dialogVisible"
          width="50%"
          @close="close"
        >
          <!-- // ~权限组From表单 -->
          <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm"
            v-if="dialogVisible"
          >
            <el-form-item label="用户名" prop="title">
              <el-input v-model="ruleForm.title"></el-input>
            </el-form-item>
            <el-form-item label="权限分配">
              <el-tree
                :data="treeData"
                show-checkbox
                node-key="id"
                :props="defaultProps"
                :default-expanded-keys="[0]"
                @check-change="ChangeTreeKeys"
                ref="Keys"
                :default-checked-keys="ruleForm.permissions"
              >
              </el-tree>
            </el-form-item>
          </el-form>

          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitForm('ruleForm')"
              >确 定</el-button
            >
          </span>
        </el-dialog>
      </div>
    </el-card>
  </div>
</template>

<script>
import { list, add, detail, update, remove } from '@/api/base/permissions.js'
import { list as menusList } from '@/api/base/menus.js'
let _this = []

export default {
  name: 'Permissions',

  data () {
    return {
      // ~输入框文本
      input: '',

      // ~From 表格
      tableData: [],
      // ~ref
      multipleSelection: [],
      // ~消息记录提示 条数
      counts: null,

      // ~当前页数
      currentPage: 1,
      // ~每页显示条目个数
      pageSize: 10,

      // ~总共条数
      total: null,
      // ~创建权限组弹框
      dialogVisible: false,
      // ~权限组表单
      ruleForm: {
        title: '',
        id: '',
        permissions: []
      },
      permissions: [],

      // ~权限组表单校验
      rules: {
        title: [{ required: true, message: '用户名不能为空', trigger: 'blur' }]
      },
      // // ~权限展示数据
      PermissionGroupsmenu: [],

      // permissionData: [],
      // ~配置选项
      defaultProps: {
        // children: 'childs' || 'points',
        // // children: 'points',
        label: 'title'
      }
    }
  },

  created () {
    _this = this
    // ~加载权限列表
    this.loadPermissionList()
    // ~加载权限展示数据
    this.loadMenusList()
  },
  computed: {
    title () {
      return this.ruleForm.id ? '编辑权限组' : '创建权限组'
    },
    treeData () {
      function createNode (item) {
        // 复选框选择
        let checked = false
        let selected = false
        if (_this !== null && _this.ruleForm.permissions.length > 0) {
          const per = _this.ruleForm.permissions.find(function (value, index) {
            return value === item.id
          })
          selected = !!per
        }
        // 标记勾选
        if (selected) {
          const isPoint = item.childs === undefined && item.points === undefined
          const hasChilds = item.childs !== undefined && item.childs.length > 0
          const hasPoints = item.points !== undefined && item.points.length > 0
          if (isPoint) {
            checked = true
          } else if (hasPoints) {
            checked = false
          } else if (hasChilds) {
            checked = false
          } else {
            checked = true
          }
        }
        return {
          id: item.id === undefined ? 0 : item.id,
          title: item.title,
          children: [],
          selected: selected,
          checked: checked
        }
      }
      function parseNodes (nodes, parentNode) {
        for (const it of nodes) {
          const node = createNode(it)
          // 标记选中
          // console.log(node.checked)
          if (node.checked) {
            parentNode.selected = true
          }
          if (it.childs !== undefined && it.childs.length > 0) {
            parseNodes(it.childs, node)
          } else if (it.points !== undefined && it.points.length > 0) {
            parseNodes(it.points, node)
          }
          parentNode.children.push(node)
        }
      }
      const nodes = createNode({ title: '系统菜单和页面权限点', expand: true })
      parseNodes(this.PermissionGroupsmenu, nodes)
      return [nodes]
    }
  },
  methods: {
    // ~加载权限列表
    async loadPermissionList () {
      const res = await list({
        title: this.input,
        page: this.currentPage,
        pagesize: this.pageSize
      })

      this.tableData = res.data.list
      this.counts = res.data.counts
      this.total = res.data.counts
    },
    // ~加载权限展示数据
    async loadMenusList () {
      // const res = await menusList()
      // this.permissionData = res.data
      // console.log(res)
      menusList().then((data) => {
        this.PermissionGroupsmenu = data.data
      })
    },
    nodeDate (nodesPath, curPermissions, findId) {
      nodesPath.map(function (item, index) {
        if (curPermissions.indexOf(item.id) === -1) {
          curPermissions.push(findId)
        }
      })
    },

    // ~当选择项发生变化时会触发该事件
    handleSelectionChange () {},
    // ~pageSize改变时会触发
    handleSizeChange (val) {
      this.pageSize = val
      this.loadPermissionList()
    },
    // ~currentPage改变时会触发
    handleCurrentChange (val) {
      this.currentPage = val
      this.loadPermissionList()
    },
    // ~输入框失去焦点或用户按下回车时触发
    async inputChange () {
      await this.loadPermissionList()
    },

    // ~搜索按钮
    SearchBtn () {
      this.loadPermissionList()
    },
    // ~清楚搜索框
    clearBtn () {
      this.input = ''
    },
    // ~权限组表单校验 确认按钮
    submitForm (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          // ~如果不存在ID 则新增 否则修改
          if (!this.ruleForm.id) {
            // ~ 如果用户未选择分配权限提示用户选择权限分配
            if (this.ruleForm.permissions.length === 0) {
              return this.$message.error('请分配权限！')
            }
            // ~校验通过！ 发起请求
            await add(this.ruleForm)
            this.$message.success('新增权限组成功！')
          } else {
            if (this.ruleForm.permissions.length === 0) {
              return this.$message.error('请分配权限！')
            }
            // ~校验通过！ 发起请求
            // ~修改编辑 当前信息

            await update(this.ruleForm)
            this.$message.success('修改权限组成功！')
          }
          // ~加载权限列表
          this.loadPermissionList()
          // ~关闭弹框
          this.dialogVisible = false
          // ~ 请求成功提示
        } else {
          return this.$message.error('请填写信息和分配权限！')
        }
      })
    },
    // ~节点改变
    ChangeTreeKeys () {
      this.ruleForm.permissions = this.$refs.Keys.getCheckedKeys()
    },
    // ~编辑权限组
    async EditBtn (id) {
      this.ruleForm.id = id
      this.dialogVisible = true
      const res = await detail(this.ruleForm)
      console.log(res)
      this.ruleForm.title = res.data.title
      this.ruleForm.permissions = res.data.permissions
    },
    // ~弹层关闭
    close () {
      // ~让数组清空
      this.defaultCheckedKeys = []
      this.$refs.ruleForm.resetFields()
      this.ruleForm = {
        title: '',
        id: '',
        permissions: []
      }
    },
    // ~新增权限组
    addFn () {
      this.dialogVisible = true
      this.$nextTick(() => {
        this.defaultCheckedKeys = []
      })
    },
    // ~删除权限组
    removeBtn (row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await remove(row)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.loadPermissionList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    // ~时间处理器
    parseTime (time, cFormat) {
      if (arguments.length === 0) {
        return null
      }

      if ((time + '').length === 10) {
        time = +time * 1000
      }

      const format = cFormat || '{y}-{m}-{d}'
      let date
      if (typeof time === 'object') {
        date = time
      } else {
        date = new Date(time)
      }
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate()
      }
      const timeStr = format.replace(/{(y|m|d)+}/g, (result, key) => {
        let value = formatObj[key]
        if (key === 'a') {
          return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
        }
        if (result.length > 0 && value < 10) {
          value = '0' + value
        }
        return value || 0
      })
      return timeStr
    }
  }
}
</script>

<style scoped lang="less">
// ~卡片样式
.box-card {
  margin: 20px;
  // ~左侧盒子
  .left-box {
    float: left;
    // ~搜素输入框
    .inputSearch {
      width: 200px;
      margin-right: 10px;
    }
  }
  // ~右侧盒子
  .right-box {
    float: right;
  }
  // ~消息提示
  .MessageAlert {
    margin-top: 50px;
    ::v-deep .el-alert__description {
      font-size: 14px;
    }
  }

  // ~From 表格
  .From-box {
    margin-top: 20px;
  }

  // ~分页
  .paging {
    margin-top: 20px;
    float: right;
    margin-bottom: 20px;
  }
  ::v-deep .el-table td.el-table__cell,
  ::v-deep .el-table th.el-table__cell.is-leaf {
    text-align: center;
  }
  ::v-deep .el-table th.is-leaf {
    border-bottom: 2px solid #e8e8e8;
    background-color: #fafafa;
  }
}
</style>
